import * as vscode from 'vscode';

/**
 * 状态栏管理器
 */
export default class StatusBarManager {
    private statusBarItem: vscode.StatusBarItem;
    private isVisible: boolean = true;
    private commands: Map<string, string> = new Map();

    constructor(private context: vscode.ExtensionContext) {
        // 创建状态栏项
        this.statusBarItem = vscode.window.createStatusBarItem(
            vscode.StatusBarAlignment.Right,
            this.getStatusBarPriority()
        );

        this.initialize();
        this.setupConfigurationListener();
    }

    /**
     * 初始化状态栏
     */
    private initialize(): void {
        // 注册命令
        this.registerCommands();
        
        // 更新状态栏显示
        this.updateStatusBar();
        
        // 根据配置显示或隐藏
        this.toggleFromConfiguration();
    }

    /**
     * 注册命令到状态栏
     */
    private registerCommands(): void {
        // 添加扩展内置命令
        this.addCommand('componentCompletion.reload', '重新加载组件配置');
        this.addCommand('componentCompletion.list', '查看已加载组件');
        this.addCommand('componentCompletion.triggerCompletion', '触发组件补全');
        // this.addCommand('componentCompletion.showCommands', '显示所有命令');

        // Logger.log(`已注册 ${this.commands.size} 个命令到状态栏`);
    }

    /**
     * 添加命令到状态栏
     */
    public addCommand(command: string, description: string): void {
        this.commands.set(command, description);
        this.updateStatusBarText();
    }

    /**
     * 移除命令
     */
    public removeCommand(command: string): void {
        this.commands.delete(command);
        this.updateStatusBarText();
    }

    /**
     * 更新状态栏文本
     */
    private updateStatusBarText(): void {
        const config = vscode.workspace.getConfiguration('componentCompletion');
        const customText = config.get<string>('statusBarText') || '$(check) Components';
        
        this.statusBarItem.text = customText;
        this.statusBarItem.tooltip = this.createTooltip();
    }

    /**
     * 创建状态栏提示文本
     */
    private createTooltip(): string {
        const commandsList = Array.from(this.commands.entries())
            .map(([command, description]) => `• ${description} (${command})`)
            .join('\n');

        return `组件补全扩展\n\n可用命令:\n${commandsList}\n\n点击查看详细信息`;
    }

    /**
     * 获取状态栏优先级
     */
    private getStatusBarPriority(): number {
        const config = vscode.workspace.getConfiguration('componentCompletion');
        return config.get<number>('statusBarPriority') || 100;
    }

    /**
     * 更新状态栏显示
     */
    private updateStatusBar(): void {
        this.statusBarItem.command = 'componentCompletion.showCommands';
        this.updateStatusBarText();
        
        if (this.isVisible) {
            this.statusBarItem.show();
        } else {
            this.statusBarItem.hide();
        }
    }

    /**
     * 根据配置切换显示状态
     */
    private toggleFromConfiguration(): void {
        const config = vscode.workspace.getConfiguration('componentCompletion');
        const showStatusBar = config.get<boolean>('showStatusBar') ?? true;
        
        this.toggle(showStatusBar);
    }

    /**
     * 切换状态栏显示
     */
    public toggle(show?: boolean): void {
        if (show !== undefined) {
            this.isVisible = show;
        } else {
            this.isVisible = !this.isVisible;
        }

        this.updateStatusBar();
        
        // Logger.log(`状态栏显示状态: ${this.isVisible ? '显示' : '隐藏'}`);
    }

    /**
     * 显示状态栏
     */
    public show(): void {
        this.toggle(true);
    }

    /**
     * 隐藏状态栏
     */
    public hide(): void {
        this.toggle(false);
    }

    /**
     * 显示可用命令列表
     */
    public async showCommands(): Promise<void> {
        const commandItems: vscode.QuickPickItem[] = Array.from(this.commands.entries()).map(
            ([command, description]) => ({
                label: description,
                description: command,
                detail: `运行命令: ${command}`
            })
        );

        // 添加管理命令
        commandItems.push(
            {
                label: '切换状态栏显示',
                description: 'componentCompletion.toggleStatusBar',
                detail: '显示或隐藏状态栏'
            },
            {
                label: '打开扩展设置',
                description: 'workbench.action.openSettings',
                detail: '配置扩展选项'
            }
        );

        const selected = await vscode.window.showQuickPick(commandItems, {
            placeHolder: '选择要执行的命令（输入命令名进行搜索）',
            matchOnDescription: true,
            matchOnDetail: true
        });

        if (selected && selected.description) {
            await vscode.commands.executeCommand(selected.description);
        }
    }

    /**
     * 设置配置变化监听
     */
    private setupConfigurationListener(): void {
        vscode.workspace.onDidChangeConfiguration((event) => {
            if (event.affectsConfiguration('componentCompletion.showStatusBar')) {
                this.toggleFromConfiguration();
            }
            
            if (event.affectsConfiguration('componentCompletion.statusBarText') ||
                event.affectsConfiguration('componentCompletion.statusBarPriority')) {
                this.updateStatusBar();
            }
        });
    }

    /**
     * 获取当前状态
     */
    public getStatus(): { isVisible: boolean; commandsCount: number } {
        return {
            isVisible: this.isVisible,
            commandsCount: this.commands.size
        };
    }

    /**
     * 销毁状态栏
     */
    public dispose(): void {
        this.statusBarItem.dispose();
        // Logger.log('状态栏已销毁');
    }
}